# -*- coding: utf-8 -*-

import logging

from webutils_wechat.auth.flask import Resource

from . import namespaces as ns
from . import marshals

logger = logging.getLogger(__name__)


@ns.auth.route('/login')
class LoginResource(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.parser.add_argument(
            'code',
            location='get_json',
        )
        self.parser.add_argument(
            'username',
            location='get_json',
        )
        self.parser.add_argument(
            'password',
            location='get_json',
        )

    @ns.auth.marshal_with(marshals.login_resp, envelope='data')
    def post(self):
        args = self.parser.parse_args()
        code = args['code']
        username = args['username']
        password = args['password']

        logger.debug('Logging in for %s %s %s', code, username, password)

        user, token = self.app.auth.login(code, username, password)

        logger.debug(
            'User logged in. id: %s openid: %s token: %s',
            user.uid,
            getattr(user, 'openid', None),
            token,
        )

        return {
            'token': token,
            'user_info': user,
        }
